package com.blyat.xsoft.kernel.util;

import com.alibaba.fastjson.JSON;
import com.blyat.xsoft.kernel.restful.view.ResultModel;
import com.google.common.base.Strings;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: syh
 * @Date: 2020/6/9
 * @Description:
 */
public class ServletUtil {

    public static ServletRequestAttributes getRequestAttributes() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }

    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }

    public static boolean isAjaxRequest() {
        return !Strings.isNullOrEmpty(getRequest().getHeader("X-Requested-With"))
                && "XMLHttpRequest".equalsIgnoreCase(getRequest().getHeader("X-Requested-With"));
    }

    public static void writer(ResultModel model) throws IOException {
        HttpServletResponse response = getResponse();
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().println(JSON.toJSONString(model));
        response.getWriter().flush();
    }

    public static String getRemoteAddr() {
        HttpServletRequest request = getRequest();
        String remoteAddr = request.getHeader("X-Real-IP");
        if (!Strings.isNullOrEmpty(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        } else if (!Strings.isNullOrEmpty(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        } else if (!Strings.isNullOrEmpty(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }

        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
    }
}
